package deepseek.deepseekr1.utils;

import org.apache.commons.lang3.StringUtils;

import javax.servlet.http.HttpServletRequest;

public class IpUtils {

    private static final String[] HEADERS_TO_CHECK = {
            "X-Forwarded-For",
            "Proxy-Client-IP",
            "WL-Proxy-Client-IP",
            "HTTP_CLIENT_IP",
            "HTTP_X_FORWARDED_FOR"
    };

    /**
     * 从 HttpServletRequest 中获取客户端真实 IP
     */
    public static String getClientIp(HttpServletRequest request) {
        if (request == null) return "unknown";

        // 遍历代理头信息
        for (String header : HEADERS_TO_CHECK) {
            String ipList = request.getHeader(header);
            if (StringUtils.isNotEmpty(ipList) && !"unknown".equalsIgnoreCase(ipList)) {
                return extractFirstValidIp(ipList);
            }
        }

        // 直接连接时的 IP
        return request.getRemoteAddr();
    }

    /**
     * 提取第一个有效 IP（支持多个 IP 场景）
     */
    private static String extractFirstValidIp(String ipStr) {
        String[] ips = ipStr.split("\\s*,\\s*");
        for (String ip : ips) {
            if (isValidIp(ip)) {
                return ip;
            }
        }
        return "unknown";
    }

    /**
     * 校验 IP 合法性（同时支持 IPv4/IPv6）
     */
    private static boolean isValidIp(String ip) {
        return StringUtils.isNotEmpty(ip) &&
                !"unknown".equalsIgnoreCase(ip) &&
                (ip.matches("^(\\d{1,3}\\.){3}\\d{1,3}$") ||  // IPv4
                        ip.matches("^([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$"));  // IPv6
    }
}
